import base64
from hashlib import md5
from random import Random
from werkzeug.security import generate_password_hash, check_password_hash

from flask import g


# 获取由6位随机大小写字母、数字组成的salt值
def create_salt(length=6):
    salt = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    len_chars = len(chars) - 1
    random = Random()
    for i in range(length):
        # 每次从chars中随机取一位
        salt += chars[random.randint(0, len_chars)]
    return salt


def md5_encode_hash(strs):
    # MD5 加盐 转哈希
    __salt = create_salt()
    md = md5()
    md.update((__salt + strs).encode(encoding='utf-8'))
    return [generate_password_hash(md.hexdigest()), __salt]


def check_password(user_password, input_password, salt):
    md = md5()
    md.update((salt + input_password).encode(encoding='utf-8'))
    return check_password_hash(user_password, md.hexdigest())


def encode_token(uid, phone):
    strs = "uid:%s&phone:%s" % (uid, phone)
    return base64.encodebytes((strs.encode())).decode()


def decode_token(key: str):
    arrs = key.split("&")
    uid = phone = None
    if not arrs:
        return None, None
    try:
        for arr in arrs:
            value = arr.split(":")
            if value[0] == "uid" and uid is None:
                uid = value[1]
            elif value[0] == "phone" and phone is None:
                phone = value[1]
        return uid, phone
    except:
        return None, None


def get_login(token):
    if token is None:
        return None, None
    try:
        key = base64.decodebytes(token.encode()).decode()
        return decode_token(key)
    except:
        return None, None


def get_login_user():
    return g.uid, g.phone
